//
//  NewPicView.m
//  CustomImagePicker
//
//  Created by kingsoft on 11-1-21.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "NewPicView.h"
#import "UIImageExtras.h"
#import "GlobalCls.h"
//#include <string>

#define kScreenWidth 320
#define kScreenHeight 480

@implementation NewPicView

@synthesize imgNewsPic;
@synthesize imgTitle;
@synthesize imgUrl;
@synthesize imgID;
@synthesize imgSaveFile;

- (id)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code.
		bInitSpinner = FALSE;
		bIsDownUrl = FALSE;
		bThreadStart = FALSE;
		//菊花使用方式
		m_spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
		[m_spinner setCenter:CGPointMake(80.0, 90.0)];

		[self addSubview:m_spinner]; // spinner is not visible until started
		bInitSpinner = TRUE;
    }
    return self;
}


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
	
	//	// create the bitmap context
	//	CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
	//	CGContextRef context = CGBitmapContextCreate(nil,100,100,8,400, colorSpace,kCGImageAlphaPremultipliedLast);
	//	CFRelease(colorSpace);
	//	
	//	//    create an arrow image
	//	// set the fill color
	//	CGColorRef fillColor = [[UIColor blackColor] CGColor];
	//	CGContextSetFillColor(context, CGColorGetComponents(fillColor));
	//	
	//	CGContextBeginPath(context);
	//	CGContextMoveToPoint(context, 8.0f, 13.0f);
	//	CGContextAddLineToPoint(context, 24.0f, 4.0f);
	//	CGContextAddLineToPoint(context, 24.0f, 22.0f);
	//	CGContextClosePath(context);
	//	CGContextFillPath(context);
	//	CGContextSelectFont ( context, "Arial", 10.f, kCGEncodingMacRoman );
	//	CGContextSetRGBFillColor ( context, 0.0f, 0.0f, 0.f, 1.f );
	//	CGContextSetShouldAntialias ( context, 0 );    
	//	CGContextShowText(context, "hh", 2);
	//	
	//	
	//	// convert the context into a CGImageRef
	//	CGImageRef image = CGBitmapContextCreateImage(context);
	//	CGContextRelease(context);
	
 	UIImage* imageDraw = [UIImage imageNamed:@"rssimg_bg.png"];
	[imageDraw drawInRect:CGRectMake(0, 0, 157, 193)];
	
	//	UIImage* image2 = [UIImage imageWithCGImage:image];
	//	[image2 drawInRect:CGRectMake(0, 0, 120, 160)];
	
	NSString* myStr = self.imgTitle;
	UIFont* font = [UIFont systemFontOfSize:12.0];
	[myStr drawInRect: CGRectMake(5, 25, 140, 30) withFont:font lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];
	
	// 当URL属性存在， 则启线程先下载再显示
	if (self.imgUrl != nil && bIsDownUrl == FALSE && bThreadStart == FALSE) {
		bThreadStart = TRUE;
//		char szBuffer[m_strImgUrl.length + 1];
//		strcpy(szBuffer, [m_strImgUrl UTF8String]);
//		crcLink = crc32(0, szBuffer, m_strImgUrl.length);

		[self startGetImgThread];
	}
	
	// 当图片存在则 绘出图片
	if (imgNewsPic != nil) {
		[[self.imgNewsPic imageByScalingAndCroppingForSize:CGSizeMake(130, 110)] drawInRect:CGRectMake(8, 60, 130, 110)];
	}
	
}

- (void)dealloc {
//	[m_strIdLink release];
//	[m_strTitle release];
//	[m_strSaveFile release];
//	[m_strImgUrl release];	
    [super dealloc];
}

-(void) startGetImgThread
{
	[m_spinner startAnimating];

	BOOL bFileExist = [[NSFileManager defaultManager] fileExistsAtPath: self.imgSaveFile];
	if (!bFileExist)
		[NSThread detachNewThreadSelector:@selector(startTheBackgroundJob:) toTarget:self withObject:self];
	else
		[self loadUrlThreadFun];
}


- (void)startTheBackgroundJob :(NewPicView *) selfPicView {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSString* strImgUrl = [[NSString alloc] initWithFormat:@"%@", selfPicView.imgUrl];
	NSString* strSaveFile = [[NSString alloc] initWithFormat:@"%@", selfPicView.imgSaveFile];

	[GlobalCls downloadFile:strImgUrl saveFile: selfPicView.imgSaveFile];
    [self performSelectorOnMainThread:@selector(loadUrlThreadFun) withObject:nil waitUntilDone:NO];
    [pool release];
	[strImgUrl release];
	[strSaveFile release];
}


-(void) refrashView
{
	[self initImgLocalFile];
	[self setNeedsDisplay];
}
	

-(void) initImgLocalFile
{
	NSString * strDocumentPath = [GlobalCls getDocumentDir];
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setDateFormat:@"yyyyMM"];
	NSDate* dateNow = [[NSDate alloc] init];
	NSString *nowDate = [formatter stringFromDate:dateNow];
	NSString* strImgPath = @"";
	strImgPath = [strImgPath stringByAppendingFormat:@"%@/%@/", strDocumentPath, nowDate];
	
	NSError* errorCreateDir;
	
	[[NSFileManager defaultManager] createDirectoryAtPath: strImgPath withIntermediateDirectories:TRUE attributes:nil error:&errorCreateDir];
	
	NSString* strSaveFile =  [strImgPath stringByAppendingFormat:@"%@_", self.imgID];
	
	NSString* strImgUrl = [[NSString alloc] initWithFormat:@"%@", self.imgUrl];
	
	NSRange rangeExtName = [strImgUrl rangeOfString:@"/" options:NSBackwardsSearch];
	if (rangeExtName.location > 0) {
		NSString* strExtname = [strImgUrl substringFromIndex:(rangeExtName.location + 1)];
		strSaveFile = [strSaveFile stringByAppendingString:strExtname];
	}
	self.imgSaveFile =  [NSString stringWithFormat:@"%@", strSaveFile];
	[strImgUrl release];
}

- (void)loadUrlThreadFun {
	BOOL bFileExist = [[NSFileManager defaultManager] fileExistsAtPath: self.imgSaveFile];
	if (bFileExist)
	{
		UIImage* imgFile = [[UIImage alloc] initWithContentsOfFile:self.imgSaveFile];
		self.imgNewsPic = [imgFile imageByScalingAndCroppingForSize:CGSizeMake(110,130)];
		[imgFile release];
	}
	bIsDownUrl = TRUE;
	bThreadStart = FALSE;
	[m_spinner stopAnimating];
	[self setNeedsDisplay];
}


@end
